﻿using CSRedis;

namespace Magic.Redis;


/// <summary>
/// 提供Redis客户端操作类（基于CsRedisCore实现）
/// </summary>
public sealed partial class CsRedisCoreClient : IRedisClient
{
	/// <summary>
	/// 获取分布式锁操作，返回false表示获取锁失败。
	/// </summary>
	/// <param name="key"></param>
	/// <param name="value"></param>
	/// <param name="expires">锁的超时时间，过期后强制释放锁</param>
	/// <returns></returns>
	public CSRedisClientLock Lock(string key, string value, TimeSpan expires)
	{
		try
		{
			var name = $"{key}:{value}";
			int.TryParse(expires.TotalSeconds.ToString(), out var seconds);
			var locker = RedisHelper.Instance.Lock(name, seconds, false);
			return locker;
		}
		catch (Exception ex)
		{
			Faild($"An exception occurs on Lock.key={key}&value={value}", ex);
			return default;
		}
	}

	/// <summary>
	/// 释放锁
	/// </summary>
	/// <param name="key"></param>
	/// <param name="value"></param>
	/// <returns></returns>
	public bool Unlock(string key, string value)
	{
		var name = $"CSRedisClientLock:{key}:{value}";
		return KeyDelete(name);
	}
}
